<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProjectRequests;
use App\Repositories\ProjectRepository;
use App\Services\Deploy;
use Illuminate\View\View;

class ProjectController extends Controller
{
    private $_projectRepository;

    public function __construct()
    {
        $this->_projectRepository = new ProjectRepository();
    }

    /**
     * 项目配置列表
     * @return View
     */
    public function index()
    {
        $paginator = $this->_projectRepository->getPageList();
        $search = request('name', '');
        return view('project.index')->with(compact(["paginator", 'search']));
    }

    /**
     * 新增项目配置视图
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('project.create');
    }

    /**
     * 添加项目配置
     * @param ProjectRequests $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(ProjectRequests $request)
    {
        $this->_projectRepository->store($request);
        return redirect('project');
    }

    /**
     * 编辑项目配置视图
     * @param $id
     * @return View
     */
    public function edit($id)
    {
        $project = $this->_projectRepository->edit($id);
        return view('project.edit')->with(compact("project"));
    }

    /**
     * 更新项目配置
     * @param ProjectRequests $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update(ProjectRequests $request, $id)
    {
        $this->_projectRepository->update($request, $id);
        return redirect('project');
    }

    /**
     * 项目配置检测
     * @return \Illuminate\Http\JsonResponse
     */
    public function detect()
    {
        $projectId = request('pid', '');
        if($projectId) {
            try {
                $detectResult = Deploy::Detection($projectId);
            } catch (\Exception $e) {
                $detectResult["code"] = -1;
                $detectResult["log"] = $e->getMessage();
            }
            return response()->json($detectResult);
        }else{
            abort(404);
        }
    }

    /**
     * 删除项目配置
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $this->_projectRepository->destroy($id);
        return redirect('project');
    }
}
